package com.jielin.handling.service.police.impl;

import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.bean.AppResult;
import com.jielin.handling.entity.auditresult.AuditResult;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.police.Cases;
import com.jielin.handling.entity.police.PoliceMan;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.entity.vo.CasePicVo;
import com.jielin.handling.entity.vo.police.ThisMonthCaseVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.auditresult.AuditResultMapper;
import com.jielin.handling.mapper.police.PoliceCaseMapper;
import com.jielin.handling.mapper.police.PoliceManMapper;
import com.jielin.handling.mapper.tsuspect.TSuspecMapper;
import com.jielin.handling.service.police.PoliceManService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.StringUtil;
import com.jielin.handling.util.VideoImageUtil;
import com.jielin.handling.util.pdfutil.PdfUtil;
import lombok.extern.slf4j.Slf4j;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.http.entity.ContentType;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.FrameGrabber;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import java.io.*;
import java.text.NumberFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class PoliceManServiceImpl implements PoliceManService {
    @Autowired
    private PoliceManMapper policeManMapper;

    @Autowired
    private TSuspecMapper tSuspecMapper;
    @Autowired
    AuditResultMapper auditResultMapper;
    @Autowired
    private PoliceManService policeManService;
    @Autowired
    private XskyService xskyService;

    @Override
    public PoliceMan findpolicmanById(String policeid) {
        PoliceMan policeMan = policeManMapper.findpolicmanById(policeid);
        if (policeMan != null) {
            if (StringUtil.isEmpty(policeMan.getHeadPhoto())) {
                if (policeMan.getSex() == 1) {
                    policeMan.setHeadPhoto(ConstantUtil.returnPoliceManPhoto());
                } else {
                    policeMan.setHeadPhoto(ConstantUtil.returnPoliceWoManPhoto());
                }
            } else {
                String returnPath = ConstantUtil.SERVER_URL + policeMan.getHeadPhoto();
                policeMan.setHeadPhoto(returnPath);
            }
        }
        return policeMan;

    }

    @Autowired
    PoliceCaseMapper mapper;

    @Override
    public List<Cases> selectCaseByCaseId(int pageNum, int pageSize, String id) {
        log.info("caseCode:{}", JSONObject.toJSONString(id));
        log.info("pageNum:{}", JSONObject.toJSONString(pageNum));
        log.info("pageSize:{}", JSONObject.toJSONString(pageSize));
        List<Cases> list = null;
        try {
            PageHelper.startPage(pageNum, pageSize);
            list = mapper.selectCaseByCaseId(id);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Map selectByCaseCode(String caseCode, String policeId) {
        log.info("caseCode:{}", JSONObject.toJSONString(caseCode));
        Map map = new HashMap();
        map.put("caseCode", caseCode);
        map.put("policeId", policeId);
        try {
            List<TSuspec> list = tSuspecMapper.selectAllSuspectByCaseCode(map);//案件关联的所有嫌疑人
            for (TSuspec tSuspec : list) {
                if (tSuspec != null) {
                    if (StringUtil.isEmpty(tSuspec.getHeadPhoto())) {
                        if (tSuspec.getSex() == 1) {
                            tSuspec.setHeadPhoto(ConstantUtil.returnManPhoto());
                        } else {
                            tSuspec.setHeadPhoto(ConstantUtil.returnWoManPhoto());
                        }
                    } else {
                        String returnPath = ConstantUtil.SERVER_URL + tSuspec.getHeadPhoto();
                        tSuspec.setHeadPhoto(returnPath);
                    }
                    if((policeId==""||policeId==null)&&tSuspec.getPoliceId()!=""){
                        policeId = tSuspec.getPoliceId();
                    }
                }
            }
            Cases cases = mapper.selectByCaseCode(map);//查询案件的详情信息
            if(caseCode !=null){
                String name =  mapper.selectPolicename(caseCode);
                String civilianPolice = name + "/" + mapper.selectPoliceId(policeId);
                cases.setCivilianpolice(civilianPolice);
            }

            int enteringCabinetAudit = auditResultMapper.selectEnteringCabinetAudit(map);//求该案件卷宗入库数量
            int allAudit = auditResultMapper.selectAudit(map);//求该案件卷宗全部数量
            // 创建一个数值格式化对象
            NumberFormat numberFormat = NumberFormat.getInstance();
            // 设置精确到小数点后2位
            numberFormat.setMaximumFractionDigits(2);
            String num = numberFormat.format((float) enteringCabinetAudit / (float) allAudit * 100);
            String Proportion = allAudit == 0 ? "0" : num;
            String drawerCode = auditResultMapper.selectDrawerCode(map);
            List<AuditResult> lists = auditResultMapper.selectAuditByCodeOrId(map);
            Map returnMap = new HashMap();
            returnMap.put("cases", cases);//案件详情信息
            returnMap.put("list", list);//案件关联和未关联嫌疑人
            returnMap.put("Proportion", Proportion);//入柜百分比
            returnMap.put("drawerCode", drawerCode);//卷宗柜号字符串
            return returnMap;
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public List<Cases> selectCaseType() {
        return mapper.selectCaseType();
    }

    @Override
    public PoliceMan login(PoliceMan policeMan) {
        log.info("policeMan:{}", JSONObject.toJSONString(policeMan));
        return policeManMapper.selectUserByLogin(policeMan);
    }

    @Override
    public List<PoliceMan> selectNameAndCode(String policeMan) {
        log.info("policeMan:{}", JSONObject.toJSONString(policeMan));
        return policeManMapper.selectNameAndCode(policeMan);
    }

    @Override
    public PoliceMan findPoliceManByCode(String policeCode) {
        if (StringUtil.isEmpty(policeCode)) {
            return null;
        }
        return policeManMapper.findPoliceManByCode(policeCode);
    }

    @Override
    public int updateLoginDate(String policeId, String ip) {
        if (StringUtil.isEmpty(policeId)) {
            return -1;
        }
        return policeManMapper.updateLoginDate(policeId, ip);
    }

    @Override
    public int savePhoto(String filePath, String id) {
        log.info("filePath:{}", JSONObject.toJSONString(filePath));
        log.info("id:{}", JSONObject.toJSONString(id));
        return policeManMapper.savePhoto(filePath, id);
    }

    @Override
    public List<CasePicVo> selectCaseByUnitcode(CasePicVo vo) {
        log.info("vo:{}", JSONObject.toJSONString(vo));
        List<CasePicVo> list = null;
        try {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            list = policeManMapper.selectCaseByUnitcode(vo);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;

    }

    //办理统计
    @Override
    public int queryInHand(JSONObject param) {

        int InHand = policeManMapper.queryInHand(param);

        return InHand;
    }

    //审核统计
    @Override
    public int queryToAudit(JSONObject param) {
        int ToAudit = policeManMapper.queryToAudit(param);
        return ToAudit;
    }

    //笔录统计
    @Override
    public int queryBiLu(JSONObject param) {
        int BiLu = policeManMapper.queryBiLu(param);
        return BiLu;
    }

    @Override
    public List<ThisMonthCaseVo> selectPersonThisMonthCaseInfo(String policeId) {
        return policeManMapper.selectPersonThisMonthCaseInfo(policeId);
    }

    @Override
    public int savePhoto2(MultipartFile file, String id, String fileString) {
//        log.info("filePath:{}", JSONObject.toJSONString(filePath));
        log.info("id:{}", JSONObject.toJSONString(id));
        boolean isHaveFile = file != null && file.getSize() > 0;
        // 表单上传文件或base64格式
        if (isHaveFile || !StringUtil.isEmpty(fileString)) {
            String path = ConstantUtil.PHOTO_PATH + "police" + File.separator + "headpic" + File.separator;
            // 文件原名称
            String trueFileName = String.valueOf(System.currentTimeMillis());
            byte[] bytes = null;
            //设置Metadata
            ObjectMetadata metadata = new ObjectMetadata();
            if (isHaveFile) {
                try {
                    String fileName = file.getOriginalFilename();
                    String fileType = fileName.substring(fileName.lastIndexOf("."));
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    bytes = file.getBytes();
                    metadata.setContentType(file.getContentType());
                    xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                    if (policeManMapper.savePhoto(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                        log.info("上传成功");
                    } else {
                        log.error("上传失败");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    log.error("xsky上传失败");
                }
            } else {
                try {
                    String fileType = ".png";
                    String filesPath = path + trueFileName + fileType;
                    filesPath = filesPath.replace("\\", "/");
                    BASE64Decoder decoder = new BASE64Decoder();
                    String base64String = fileString.substring(fileString.indexOf(",") + 1);// 去掉头部（不能解析）
                    log.info("Base64解码后:\n" + base64String);
//                    byte[] b = new byte[0];
                    bytes = decoder.decodeBuffer(base64String);
                    for (int i = 0; i < bytes.length; ++i) {
                        if (bytes[i] < 0) {// 调整异常数据
                            bytes[i] += 256;
                        }
                    }
                    try {
                        metadata.setContentType(ContentType.IMAGE_JPEG.getMimeType());
                        xskyService.uploadObjectForInputStream(ConstantUtil.XSKY_BUCKET_PHOTO, filesPath, bytes, metadata);
                        if (policeManMapper.savePhoto(ConstantUtil.XSKY_PHOTO_URL + filesPath, id) > 0) {
                            log.info("上传成功");
                        } else {
                            log.error("上传失败");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error("xsky上传失败！");
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                    return ResultEnum.FAIL.getCode();
                }
            }

            return ResultEnum.SUCCESS.getCode();
        }
        return ResultEnum.FAIL.getCode();
    }

}
